package com.manhhavu.bemas.dao.hibernateimpl;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.manhhavu.bemas.business.objects.link.ClickedLink;
import com.manhhavu.bemas.dao.ClickedLinkDAO;

public class ClickedLinkDAOHibernateImpl implements ClickedLinkDAO{

	@Override
	public List<ClickedLink> getAll() {
		List<ClickedLink> linkList = null;
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		
		try {
			transaction = session.beginTransaction();
			linkList = (List<ClickedLink>) session.createQuery("from ClickedLink").list();			
			transaction.commit();
		} catch(HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return linkList;
	}

	@Override
	public Long save(ClickedLink link) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		Long id = null;
		
		try {
			transaction = session.beginTransaction();
			id = (Long) session.save(link);			
			transaction.commit();
		} catch(HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return id;
	}

	@Override
	public void delete(long id) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		
		try {
			transaction = session.beginTransaction();
			ClickedLink link = (ClickedLink) session.get(ClickedLink.class, new Long(id));
			session.delete(link);
			transaction.commit();
		} catch(HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}
	
}
